package com.s1nx.back.service.impl;

import com.s1nx.back.dao.UserDao;
import com.s1nx.back.entity.User;
import com.s1nx.back.exception.ServiceException;
import com.s1nx.back.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.text.SimpleDateFormat;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User login(User user) {

        User userByUsername = userDao.getUserByUsername(user);
        if (userByUsername == null) {
            throw new ServiceException("用户名不存在" + user.getUsername());
        } else if (userByUsername.getPassword().equals(user.getPassword())) {
            return userByUsername;
        }
        throw new ServiceException("用户名或者密码错误!");
    }

    @Override
    public User register(User user) {
        User userByUsername = userDao.getUserByUsername(user);
        if (userByUsername != null) {
            throw new ServiceException("用户名已存在" + user.getUsername());
        }

        //获取当前系统时间, 并格式化时间yyyy-MM-dd HH:mm:ss
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()));
        user.setCreateTime(format);
        user.setUpdateTime(format);

        int i = userDao.insertUser(user);
        if (i == 1) {
            return user;
        }
        throw new ServiceException("注册失败");
    }
}
